<!DOCTYPE html>




<html class="theme-next gemini" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
    
  
  <link href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|Source Code Pro:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="https://cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.css" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.0.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="32x32" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="16x16" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="mask-icon" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0" color="#222">





  <meta name="keywords" content="vps, java, python, golang, springmvc">




  


  <link rel="alternate" href="/atom.xml" title="张恒的网络日志" type="application/atom+xml">






<meta name="keywords" content="java, python, go, 技术, 学习笔记, spring">
<meta property="og:type" content="website">
<meta property="og:title" content="张恒的网络日志">
<meta property="og:url" content="http://blog.gavinzh.com/404.html">
<meta property="og:site_name" content="张恒的网络日志">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-01-05T08:52:36.912Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="张恒的网络日志">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.0.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    fastclick: true,
    lazyload: true,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.gavinzh.com/404.html">





  <title>SpringMVC 解毒5 | 张恒的网络日志</title>
  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-98061925-1', 'auto');
  ga('send', 'pageview');
</script>





</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">张恒的网络日志</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Zhang Heng's WebSite Blog</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.gavinzh.com/2018/08/29/learn-springmvc-code-5/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Gavin Zhang">
      <meta itemprop="description" content>
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/5567916">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="张恒的网络日志">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">SpringMVC 解毒5</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-29T11:09:00+00:00">2018-08-29</time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/笔记/" itemprop="url" rel="index">
                    <span itemprop="name">笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/08/29/learn-springmvc-code-5/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/08/29/learn-springmvc-code-5/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2018/08/29/learn-springmvc-code-5/" class="leancloud_visitors" data-flag-title="SpringMVC 解毒5">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="7-MultipartResolver"><a href="#7-MultipartResolver" class="headerlink" title="7 MultipartResolver"></a>7 MultipartResolver</h2><img src="http://www.plantuml.com/plantuml/svg/ZL9B3e8m4Dtt50rxUWBZqkZ2ZPoWaW4hdzQX1HFr5kvTUWVFO-8rR2G4fO1qqKNVUtqpRuOe7YOy1YenPeL2aSSHyWmgYGchOCioasgXE6fw8eJQ8t8D6F4GwBg1Db38j0JyuCEaWu52ZtAMMgi0i4nX4dqXKcW9xTNrfBEpxqzpSQI-FwVUyt5_NM_UaBCJn82gnvXS26b6iESbFxAY9jYuUrhlg8V4R6UT-dyOQ_xtlKvjZEzY_vEs9PEndGib0XFItRPLhemED0BF0cam_ChVWJfbVAPbZTy0">

<a id="more"></a>

<p>还记得我们在第二章讲<code>DispatcherServlet</code>时提到的<code>MultipartResolver</code>吗？</p>
<p>2.3.1节讲到 initMultipartResolver() 方法会尝试从web应用上下文中获取beanName为<code>multipartResolver</code>的<code>MultipartResolver</code>实现类。</p>
<p>2.4.2节讲到在真正处理request前会先判断请求是不是携带multipart文本格式，如果携带，则会把request转为<code>MultipartHttpServletRequest</code>。在使用完<code>MultipartHttpServletRequest</code>后需要清除生成<code>MultipartHttpServletRequest</code>时产生的临时文件。</p>
<p><code>MultipartResolver</code>最重要的功能就是能够解析前端通过post请求上传的文件，接下来让我们深入了解<code>MultipartResolver</code>。</p>
<h3 id="7-1-MultipartResolver-分析"><a href="#7-1-MultipartResolver-分析" class="headerlink" title="7.1 MultipartResolver 分析"></a>7.1 MultipartResolver 分析</h3><p><code>DispatcherServlet</code>使用的是<code>MultipartResolver</code>接口，什么意思呢？我们只要把握住<code>MultipartResolver</code>接口中的方法，那么就能掌握<code>MultipartResolver</code>的使用。</p>
<img src="http://www.plantuml.com/plantuml/svg/ZOux3i8m38RtdC8Z2ActG69XWHEamGrHqpWuReE4UdV2g-s04F_YmT__K56RLbi4Obkbo2xOXdM7cRYjCjPLrtjnKRF0JIaeSa6G6sqGzf_N0HFv0RaWyDO6QYAFEe1B4xVQYSGZyk2nU2uz9W5-tVN2EV5VyMVLNv4WPwQSvhpjrM0KHs5HDf0xWNaixUES-dl2Ol6eHdK7">

<p>MultipartResolver 接口提供了三个方法。isMultipart 方法是用来判断request是不是含有multipart内容，resolveMultipart 方法用来生成<code>MultipartHttpServletRequest</code>，cleanupMultipart 方法则是在使用完<code>MultipartHttpServletRequest</code>后清除临时资源文件的。</p>
<p>实际上<code>DispatcherServlet</code>的 checkMultipart 方法先调用了 isMultipart 方法，然后调用了 resolveMultipart 方法生成 MultipartHttpServletRequest。来看代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Convert the request into a multipart request, and make multipart resolver available.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;If no multipart resolver is set, simply use the existing request.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the processed request (multipart wrapper if necessary)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> MultipartResolver#resolveMultipart</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> HttpServletRequest <span class="title">checkMultipart</span><span class="params">(HttpServletRequest request)</span> <span class="keyword">throws</span> MultipartException </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (<span class="keyword">this</span>.multipartResolver != <span class="keyword">null</span> &amp;&amp; <span class="keyword">this</span>.multipartResolver.isMultipart(request)) &#123;</span><br><span class="line">		<span class="keyword">if</span> (WebUtils.getNativeRequest(request, MultipartHttpServletRequest<span class="class">.<span class="keyword">class</span>) !</span>= <span class="keyword">null</span>) &#123;</span><br><span class="line">			logger.debug(<span class="string">"Request is already a MultipartHttpServletRequest - if not in a forward, "</span> +</span><br><span class="line">					<span class="string">"this typically results from an additional MultipartFilter in web.xml"</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span> (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) <span class="keyword">instanceof</span> MultipartException) &#123;</span><br><span class="line">			logger.debug(<span class="string">"Multipart resolution failed for current request before - "</span> +</span><br><span class="line">					<span class="string">"skipping re-resolution for undisturbed error rendering"</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">this</span>.multipartResolver.resolveMultipart(request);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// If not returned before: return original request.</span></span><br><span class="line">	<span class="keyword">return</span> request;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>而后，在2.4.2节doDispatch方法的第88行到第93行，判断如果这个请求没有使用异步响应技术，那么就会调用 cleanupMultipart 方法清除临时资源。代码如下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Clean up any resources used by the given multipart request (if any).</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> MultipartResolver#cleanupMultipart</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">cleanupMultipart</span><span class="params">(HttpServletRequest request)</span> </span>&#123;</span><br><span class="line">	MultipartHttpServletRequest multipartRequest =</span><br><span class="line">			WebUtils.getNativeRequest(request, MultipartHttpServletRequest<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">	<span class="keyword">if</span> (multipartRequest != <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">this</span>.multipartResolver.cleanupMultipart(multipartRequest);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="7-2-CommonsMultipartResolver-分析"><a href="#7-2-CommonsMultipartResolver-分析" class="headerlink" title="7.2 CommonsMultipartResolver 分析"></a>7.2 CommonsMultipartResolver 分析</h3><img src="http://www.plantuml.com/plantuml/svg/hOyn3i8m34Ntd28NQ4x0Wf3OMAWuW1lSAcfIHuxR8a7lJjMgOg051Znuy7_IVrOHR0qLQkBAfCYkgKg6W3rnRNeiJ6Yzk0Winb88r2HzLqgFOpsaf0_pyRHGPqpaE-G9cHOKIHYiBEZHURn4Jt3DsnY9vOLk4NhtoBBjAZKezVCRYxvh1Ba4Y_g3-rlq1nDBO_DjnID7xZpAOSxtFJ1EnChzYyQWdW00">


<p>在常见的web项目总中，我们都会使用<code>CommonsMultipartResolver</code>这个实现类，它实际上使用了 <a href="http://commons.apache.org/proper/commons-fileupload" target="_blank" rel="noopener">Apache Commons FileUpload</a>。</p>
<h4 id="7-2-1-CommonsMultipartResolver-初始化分析"><a href="#7-2-1-CommonsMultipartResolver-初始化分析" class="headerlink" title="7.2.1 CommonsMultipartResolver 初始化分析"></a>7.2.1 CommonsMultipartResolver 初始化分析</h4><p>由于这个类也比较复杂，我们还是从初始化说起，看看它都会做哪些事情。</p>
<p>首先，因为它继承了抽象类<code>CommonsFileUploadSupport</code>，而在这个类的构造方法中又会调用抽象方法<code>protected abstract FileUpload newFileUpload(FileItemFactory fileItemFactory)</code>，所以，我们将目光转向这个方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Initialize the underlying &#123;<span class="doctag">@code</span> org.apache.commons.fileupload.servlet.ServletFileUpload&#125;</span></span><br><span class="line"><span class="comment"> * instance. Can be overridden to use a custom subclass, e.g. for testing purposes.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> fileItemFactory the Commons FileItemFactory to use</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the new ServletFileUpload instance</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> FileUpload <span class="title">newFileUpload</span><span class="params">(FileItemFactory fileItemFactory)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">new</span> ServletFileUpload(fileItemFactory);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>重写的方法还是很简单的，直接创建了一个新的ServletFileUpload类。</p>
<p>接下来，由于它还实现了ServletContextAware方法，所以我们来找找setServletContext方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setServletContext</span><span class="params">(ServletContext servletContext)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (!isUploadTempDirSpecified()) &#123;</span><br><span class="line">		getFileItemFactory().setRepository(WebUtils.getTempDir(servletContext));</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// CommonsFileUploadSupport.java</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">boolean</span> <span class="title">isUploadTempDirSpecified</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">this</span>.uploadTempDirSpecified;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// WebUtils.java</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Standard Servlet spec context attribute that specifies a temporary</span></span><br><span class="line"><span class="comment"> * directory for the current web application, of type &#123;<span class="doctag">@code</span> java.io.File&#125;.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String TEMP_DIR_CONTEXT_ATTRIBUTE = <span class="string">"javax.servlet.context.tempdir"</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Return the temporary directory for the current web application,</span></span><br><span class="line"><span class="comment"> * as provided by the servlet container.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> servletContext the servlet context of the web application</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the File representing the temporary directory</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> File <span class="title">getTempDir</span><span class="params">(ServletContext servletContext)</span> </span>&#123;</span><br><span class="line">	Assert.notNull(servletContext, <span class="string">"ServletContext must not be null"</span>);</span><br><span class="line">	<span class="keyword">return</span> (File) servletContext.getAttribute(TEMP_DIR_CONTEXT_ATTRIBUTE);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到，这个方法实际上是给FileItemFactory设置一个仓库地址，而仓库地址的类型是File，而这个File对象则是通过标准的servletContext属性<code>javax.servlet.context.tempdir</code>取得。</p>
<p>而什么时候不从servletContext属性中取得呢？来看看代码</p>
<p>CommonsFileUploadSupport.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Set the temporary directory where uploaded files get stored.</span></span><br><span class="line"><span class="comment"> * Default is the servlet container's temporary directory for the web application.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.web.util.WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setUploadTempDir</span><span class="params">(Resource uploadTempDir)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (!uploadTempDir.exists() &amp;&amp; !uploadTempDir.getFile().mkdirs()) &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Given uploadTempDir ["</span> + uploadTempDir + <span class="string">"] could not be created"</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">this</span>.fileItemFactory.setRepository(uploadTempDir.getFile());</span><br><span class="line">	<span class="keyword">this</span>.uploadTempDirSpecified = <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果我们设置了别的临时目录，就不会从servletContext属性中获取了。</p>
<h4 id="7-2-2-CommonsMultipartResolver-属性设置分析"><a href="#7-2-2-CommonsMultipartResolver-属性设置分析" class="headerlink" title="7.2.2 CommonsMultipartResolver 属性设置分析"></a>7.2.2 CommonsMultipartResolver 属性设置分析</h4><p>初始化代码我们已经看完了，接下来让我们再来了解了解可以设置的属性。</p>
<ul>
<li><p>第一个就是uploadTempDirSpecified，它是通过setUploadTempDir方法设置的，也就是说，如果你设置了临时目录，那这个属性会变成true。</p>
</li>
<li><p>接下来有一个setDefaultEncoding方法，这个方法会指定multipart部分内容的字符编码格式，一般我们会设置成<code>UTF-8</code>。如果不设置并且从header中没有找到charset，默认是<code>ISO-8859-1</code>，原因可以看代码：</p>
</li>
</ul>
<p>CommonsFileUploadSupport.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Set the default character encoding to use for parsing requests,</span></span><br><span class="line"><span class="comment"> * to be applied to headers of individual parts and to form fields.</span></span><br><span class="line"><span class="comment"> * Default is ISO-8859-1, according to the Servlet spec.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;If the request specifies a character encoding itself, the request</span></span><br><span class="line"><span class="comment"> * encoding will override this setting. This also allows for generically</span></span><br><span class="line"><span class="comment"> * overriding the character encoding in a filter that invokes the</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@code</span> ServletRequest.setCharacterEncoding&#125; method.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> defaultEncoding the character encoding to use</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> javax.servlet.ServletRequest#getCharacterEncoding</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> javax.servlet.ServletRequest#setCharacterEncoding</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> WebUtils#DEFAULT_CHARACTER_ENCODING</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.apache.commons.fileupload.FileUploadBase#setHeaderEncoding</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setDefaultEncoding</span><span class="params">(String defaultEncoding)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">this</span>.fileUpload.setHeaderEncoding(defaultEncoding);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> String <span class="title">getDefaultEncoding</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	String encoding = getFileUpload().getHeaderEncoding();</span><br><span class="line">	<span class="keyword">if</span> (encoding == <span class="keyword">null</span>) &#123;</span><br><span class="line">		encoding = WebUtils.DEFAULT_CHARACTER_ENCODING;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> encoding;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>WebUtils.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Default character encoding to use when &#123;<span class="doctag">@code</span> request.getCharacterEncoding&#125;</span></span><br><span class="line"><span class="comment"> * returns &#123;<span class="doctag">@code</span> null&#125;, according to the Servlet spec.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> ServletRequest#getCharacterEncoding</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String DEFAULT_CHARACTER_ENCODING = <span class="string">"ISO-8859-1"</span>;</span><br></pre></td></tr></table></figure>

<ul>
<li><p>第三个是setMaxUploadSize方法，这个方法的作用是当content大小大于maxUploadSize或者读取到maxUploadSize大小字节数据后还有内容，会抛出<code>SizeLimitExceededException</code>异常。</p>
</li>
<li><p>第四个是setMaxInMemorySize方法，这个方法指定上传的文件如果没超过maxInMemorySize字节大小，则不会真正写到文件，而是保留在内存数组中。如果想了解具体如何操作的，可以参考<code>org.apache.commons.io.output.ThresholdingOutputStream</code>带阈值的outputstream。</p>
</li>
<li><p>第五个是setMaxUploadSizePerFile方法，这个方法限定每一个文件的最大大小，当其中的一个文件大小超过maxUploadSizePerFile或者读取到maxUploadSizePerFile大小字节数据后还有内容，会抛出<code>FileSizeLimitExceededException</code>。</p>
</li>
<li><p>第六个是setResolveLazily方法，这六个方法只有这个方法是CommonsMultipartResolver类所拥有的，其余均是CommonsFileUploadSupport类所拥有的。这个参数的作用是延后解析multipart数据，当resolveLazily属性为true，只有在真正用到multipart部分数据时才会进行解析。来看代码：</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> MultipartHttpServletRequest <span class="title">resolveMultipart</span><span class="params">(<span class="keyword">final</span> HttpServletRequest request)</span> <span class="keyword">throws</span> MultipartException </span>&#123;</span><br><span class="line">	Assert.notNull(request, <span class="string">"Request must not be null"</span>);</span><br><span class="line">	<span class="keyword">if</span> (<span class="keyword">this</span>.resolveLazily) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">new</span> DefaultMultipartHttpServletRequest(request) &#123;</span><br><span class="line">			<span class="meta">@Override</span></span><br><span class="line">			<span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initializeMultipart</span><span class="params">()</span> </span>&#123;</span><br><span class="line">				MultipartParsingResult parsingResult = parseRequest(request);</span><br><span class="line">				setMultipartFiles(parsingResult.getMultipartFiles());</span><br><span class="line">				setMultipartParameters(parsingResult.getMultipartParameters());</span><br><span class="line">				setMultipartParameterContentTypes(parsingResult.getMultipartParameterContentTypes());</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> &#123;</span><br><span class="line">		MultipartParsingResult parsingResult = parseRequest(request);</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">new</span> DefaultMultipartHttpServletRequest(request, parsingResult.getMultipartFiles(),</span><br><span class="line">				parsingResult.getMultipartParameters(), parsingResult.getMultipartParameterContentTypes());</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="7-2-3-CommonsMultipartResolver-处理请求分析"><a href="#7-2-3-CommonsMultipartResolver-处理请求分析" class="headerlink" title="7.2.3 CommonsMultipartResolver 处理请求分析"></a>7.2.3 CommonsMultipartResolver 处理请求分析</h4><p>CommonsMultipartResolver 的初始化和可注入的属性我们已经分析过了，我们发现它可以限制单个文件大小和整个multipart大小，临时文件磁盘存放等等。接下来，我们就来看看它是如何解析请求的。</p>
<p>首先来看看如何判断是不是multipart</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// CommonsMultipartResolver.java</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isMultipart</span><span class="params">(HttpServletRequest request)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> (request != <span class="keyword">null</span> &amp;&amp; ServletFileUpload.isMultipartContent(request));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// org.apache.commons.fileupload.servlet.ServletFileUpload.java</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Utility method that determines whether the request contains multipart</span></span><br><span class="line"><span class="comment"> * content.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request The servlet request to be evaluated. Must be non-null.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> &lt;code&gt;true&lt;/code&gt; if the request is multipart;</span></span><br><span class="line"><span class="comment"> *         &lt;code&gt;false&lt;/code&gt; otherwise.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">isMultipartContent</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        HttpServletRequest request)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!POST_METHOD.equalsIgnoreCase(request.getMethod())) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> FileUploadBase.isMultipartContent(<span class="keyword">new</span> ServletRequestContext(request));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// org.apache.commons.fileupload.FileUploadBase</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Utility method that determines whether the request contains multipart</span></span><br><span class="line"><span class="comment"> * content.&lt;/p&gt;</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;&lt;strong&gt;<span class="doctag">NOTE:</span>&lt;/strong&gt;This method will be moved to the</span></span><br><span class="line"><span class="comment"> * &lt;code&gt;ServletFileUpload&lt;/code&gt; class after the FileUpload 1.1 release.</span></span><br><span class="line"><span class="comment"> * Unfortunately, since this method is static, it is not possible to</span></span><br><span class="line"><span class="comment"> * provide its replacement until this method is removed.&lt;/p&gt;</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> ctx The request context to be evaluated. Must be non-null.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> &lt;code&gt;true&lt;/code&gt; if the request is multipart;</span></span><br><span class="line"><span class="comment"> *         &lt;code&gt;false&lt;/code&gt; otherwise.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">isMultipartContent</span><span class="params">(RequestContext ctx)</span> </span>&#123;</span><br><span class="line">    String contentType = ctx.getContentType();</span><br><span class="line">    <span class="keyword">if</span> (contentType == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (contentType.toLowerCase(Locale.ENGLISH).startsWith(MULTIPART)) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Part of HTTP content type header.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String MULTIPART = <span class="string">"multipart/"</span>;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>看源码的时候发现一个事，spring的源码都是用<code>tab</code>缩进，而apache的源码采用空格缩进。</p>
</blockquote>
<p>我们可以看到，判断规则交给了apache-common-fileupload，其规则就是：必须是post请求，content-Type必须以<code>multipart/</code>开头。</p>
<p>看完判断接下来再看看如何解析请求。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> MultipartHttpServletRequest <span class="title">resolveMultipart</span><span class="params">(<span class="keyword">final</span> HttpServletRequest request)</span> <span class="keyword">throws</span> MultipartException </span>&#123;</span><br><span class="line">	Assert.notNull(request, <span class="string">"Request must not be null"</span>);</span><br><span class="line">	<span class="keyword">if</span> (<span class="keyword">this</span>.resolveLazily) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">new</span> DefaultMultipartHttpServletRequest(request) &#123;</span><br><span class="line">			<span class="meta">@Override</span></span><br><span class="line">			<span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initializeMultipart</span><span class="params">()</span> </span>&#123;</span><br><span class="line">				MultipartParsingResult parsingResult = parseRequest(request);</span><br><span class="line">				setMultipartFiles(parsingResult.getMultipartFiles());</span><br><span class="line">				setMultipartParameters(parsingResult.getMultipartParameters());</span><br><span class="line">				setMultipartParameterContentTypes(parsingResult.getMultipartParameterContentTypes());</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> &#123;</span><br><span class="line">		MultipartParsingResult parsingResult = parseRequest(request);</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">new</span> DefaultMultipartHttpServletRequest(request, parsingResult.getMultipartFiles(),</span><br><span class="line">				parsingResult.getMultipartParameters(), parsingResult.getMultipartParameterContentTypes());</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Parse the given servlet request, resolving its multipart elements.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request the request to parse</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the parsing result</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> MultipartException if multipart resolution failed.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> MultipartParsingResult <span class="title">parseRequest</span><span class="params">(HttpServletRequest request)</span> <span class="keyword">throws</span> MultipartException </span>&#123;</span><br><span class="line">	String encoding = determineEncoding(request);</span><br><span class="line">	FileUpload fileUpload = prepareFileUpload(encoding);</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		List&lt;FileItem&gt; fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);</span><br><span class="line">		<span class="keyword">return</span> parseFileItems(fileItems, encoding);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (FileUploadBase.SizeLimitExceededException ex) &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (FileUploadException ex) &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> MultipartException(<span class="string">"Could not parse multipart servlet request"</span>, ex);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们这里以实时解析为例，实际上，DefaultMultipartHttpServletRequest会在调用multipart部分内容是判断有没有初始化，如果没有就会调用初始化方法。</p>
<p>CommonsMultipartResolver 在解析时调用 parseRequest 方法得到解析的内容，然后将解析的内容通过构造函数置入 DefaultMultipartHttpServletRequest。所以接下来继续看CommonsFileUploadSupport类。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Determine an appropriate FileUpload instance for the given encoding.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Default implementation returns the shared FileUpload instance</span></span><br><span class="line"><span class="comment"> * if the encoding matches, else creates a new FileUpload instance</span></span><br><span class="line"><span class="comment"> * with the same configuration other than the desired encoding.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> encoding the character encoding to use</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> an appropriate FileUpload instance.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> FileUpload <span class="title">prepareFileUpload</span><span class="params">(String encoding)</span> </span>&#123;</span><br><span class="line">	FileUpload fileUpload = getFileUpload();</span><br><span class="line">	FileUpload actualFileUpload = fileUpload;</span><br><span class="line">	<span class="comment">// Use new temporary FileUpload instance if the request specifies</span></span><br><span class="line">	<span class="comment">// its own encoding that does not match the default encoding.</span></span><br><span class="line">	<span class="keyword">if</span> (encoding != <span class="keyword">null</span> &amp;&amp; !encoding.equals(fileUpload.getHeaderEncoding())) &#123;</span><br><span class="line">		actualFileUpload = newFileUpload(getFileItemFactory());</span><br><span class="line">		actualFileUpload.setSizeMax(fileUpload.getSizeMax());</span><br><span class="line">		actualFileUpload.setFileSizeMax(fileUpload.getFileSizeMax());</span><br><span class="line">		actualFileUpload.setHeaderEncoding(encoding);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> actualFileUpload;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Parse the given List of Commons FileItems into a Spring MultipartParsingResult,</span></span><br><span class="line"><span class="comment"> * containing Spring MultipartFile instances and a Map of multipart parameter.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> fileItems the Commons FileIterms to parse</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> encoding the encoding to use for form fields</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the Spring MultipartParsingResult</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> CommonsMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> MultipartParsingResult <span class="title">parseFileItems</span><span class="params">(List&lt;FileItem&gt; fileItems, String encoding)</span> </span>&#123;</span><br><span class="line">	MultiValueMap&lt;String, MultipartFile&gt; multipartFiles = <span class="keyword">new</span> LinkedMultiValueMap&lt;String, MultipartFile&gt;();</span><br><span class="line">	Map&lt;String, String[]&gt; multipartParameters = <span class="keyword">new</span> HashMap&lt;String, String[]&gt;();</span><br><span class="line">	Map&lt;String, String&gt; multipartParameterContentTypes = <span class="keyword">new</span> HashMap&lt;String, String&gt;();</span><br><span class="line">	<span class="comment">// Extract multipart files and multipart parameters.</span></span><br><span class="line">	<span class="keyword">for</span> (FileItem fileItem : fileItems) &#123;</span><br><span class="line">		<span class="keyword">if</span> (fileItem.isFormField()) &#123;</span><br><span class="line">			String value;</span><br><span class="line">			String partEncoding = determineEncoding(fileItem.getContentType(), encoding);</span><br><span class="line">			<span class="keyword">if</span> (partEncoding != <span class="keyword">null</span>) &#123;</span><br><span class="line">				<span class="keyword">try</span> &#123;</span><br><span class="line">					value = fileItem.getString(partEncoding);</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">catch</span> (UnsupportedEncodingException ex) &#123;</span><br><span class="line">					<span class="keyword">if</span> (logger.isWarnEnabled()) &#123;</span><br><span class="line">						logger.warn(<span class="string">"Could not decode multipart item '"</span> + fileItem.getFieldName() +</span><br><span class="line">								<span class="string">"' with encoding '"</span> + partEncoding + <span class="string">"': using platform default"</span>);</span><br><span class="line">					&#125;</span><br><span class="line">					value = fileItem.getString();</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> &#123;</span><br><span class="line">				value = fileItem.getString();</span><br><span class="line">			&#125;</span><br><span class="line">			String[] curParam = multipartParameters.get(fileItem.getFieldName());</span><br><span class="line">			<span class="keyword">if</span> (curParam == <span class="keyword">null</span>) &#123;</span><br><span class="line">				<span class="comment">// simple form field</span></span><br><span class="line">				multipartParameters.put(fileItem.getFieldName(), <span class="keyword">new</span> String[] &#123;value&#125;);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> &#123;</span><br><span class="line">				<span class="comment">// array of simple form fields</span></span><br><span class="line">				String[] newParam = StringUtils.addStringToArray(curParam, value);</span><br><span class="line">				multipartParameters.put(fileItem.getFieldName(), newParam);</span><br><span class="line">			&#125;</span><br><span class="line">			multipartParameterContentTypes.put(fileItem.getFieldName(), fileItem.getContentType());</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="comment">// multipart file field</span></span><br><span class="line">			CommonsMultipartFile file = <span class="keyword">new</span> CommonsMultipartFile(fileItem);</span><br><span class="line">			multipartFiles.add(file.getName(), file);</span><br><span class="line">			<span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">				logger.debug(<span class="string">"Found multipart file ["</span> + file.getName() + <span class="string">"] of size "</span> + file.getSize() +</span><br><span class="line">						<span class="string">" bytes with original filename ["</span> + file.getOriginalFilename() + <span class="string">"], stored "</span> +</span><br><span class="line">						file.getStorageDescription());</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">new</span> MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>prepareFileUpload 方法很简单，入参是编码方式，获取的时FileUpload实现类对象。中间有这么一折，因为我们最开始置入了编码方式，如果从request请求中获得的编码方式和最开始设置的不一致，它会创建一个新的FileUpload实现类对象。所以，一定要设置默认编码方式，否则，如果请求和默认编码方式不一致，每次都要创建新的FileUpload实现类对象。</p>
<p>parseFileItems 方法是其最重要的方法，apache-common-fileupload中FileUpload实现类将请求中的content解析成FileItem列表，FileItem列表解析成multipart都在这里进行。</p>
<p>首先在代码第33行到第35行，声明了我们需要的multipartFile的map、multipart中的键值和multipart中的contentType。接下来就是从FileItem列表中解析数据。</p>
<p>代码第39行到第66行，处理的是键值，因为一个键可以对应多个值，所以Map的值类型为<code>String[]</code>，它允许值有多个。每一个FileItem中只有一个值，所以这块代码要判断<code>MultiValueMap</code>中key有没有值，有值就把新的值加入到旧的数组中，没有就创建一个新数组。</p>
<p>代码第68行到第77行，处理的是文件类型的数据。因为一个key可能对应多个文件，apache-common设计了一个<code>MultiValueMap</code>，它的值是泛型列表，如果add时key已经有value了，新值会被加到value列表中。</p>
<blockquote>
<p>读者请注意，我这里故意略过了实际的解析过程，如果你想了解最详细的解析过程，可以参考<code>org.apache.commons.fileupload.FileUploadBase#parseRequest</code>，这个方法内是真正的解析过程。</p>
</blockquote>
<h4 id="7-2-4-CommonsMultipartResolver-结束请求分析"><a href="#7-2-4-CommonsMultipartResolver-结束请求分析" class="headerlink" title="7.2.4 CommonsMultipartResolver 结束请求分析"></a>7.2.4 CommonsMultipartResolver 结束请求分析</h4><p>当<code>DispathcerServlet</code>调用 cleanupMultipart 方法时，会调用 CommonsMultipartResolver 的 cleanupMultipart 方法，最终调用的则是 CommonsFileUploadSupport 的 cleanupFileItems 方法。</p>
<p>CommonsMultipartResolver.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">cleanupMultipart</span><span class="params">(MultipartHttpServletRequest request)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (request != <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			cleanupFileItems(request.getMultiFileMap());</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">			logger.warn(<span class="string">"Failed to perform multipart cleanup for servlet request"</span>, ex);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>CommonsFileUploadSupport.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Cleanup the Spring MultipartFiles created during multipart parsing,</span></span><br><span class="line"><span class="comment"> * potentially holding temporary data on disk.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Deletes the underlying Commons FileItem instances.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> multipartFiles Collection of MultipartFile instances</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.apache.commons.fileupload.FileItem#delete()</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">cleanupFileItems</span><span class="params">(MultiValueMap&lt;String, MultipartFile&gt; multipartFiles)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">for</span> (List&lt;MultipartFile&gt; files : multipartFiles.values()) &#123;</span><br><span class="line">		<span class="keyword">for</span> (MultipartFile file : files) &#123;</span><br><span class="line">			<span class="keyword">if</span> (file <span class="keyword">instanceof</span> CommonsMultipartFile) &#123;</span><br><span class="line">				CommonsMultipartFile cmf = (CommonsMultipartFile) file;</span><br><span class="line">				cmf.getFileItem().delete();</span><br><span class="line">				<span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">					logger.debug(<span class="string">"Cleaning up multipart file ["</span> + cmf.getName() + <span class="string">"] with original filename ["</span> +</span><br><span class="line">							cmf.getOriginalFilename() + <span class="string">"], stored "</span> + cmf.getStorageDescription());</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到，我们之前把multipart解析成两中类型的数据，一种是键值，另一种是键文件。需要清除的是键文件，而在 7.2.2 节讲第四个属性setMaxInMemorySize方法时，提到过，如果文件大小超过指定字节数，会被写到临时文件目录中，所以这里做的就是清除临时目录文件。</p>
<h4 id="7-2-5-什么是multipart请求"><a href="#7-2-5-什么是multipart请求" class="headerlink" title="7.2.5 什么是multipart请求"></a>7.2.5 什么是multipart请求</h4><p>以上几个小节，我们只是简单的了解了如何判断是不是需要解析multipart，解析成FileItem后如何转为Spring中的MultipartFile和其他属性，请求结束时如何销毁临时文件等这样的功能。我略过了<code>FileUpload</code>实现类解析请求成<code>FileItem</code>列表的过程。</p>
<p>HTTP协议规范规定，如果想提交一个multipart请求，首先方法必须是post方法，header中Content-Type格式需为<code>Content-Type: multipart/form-data; boundary=${bound}</code>，其Content内容格式如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">--$&#123;bound&#125;</span><br><span class="line">Content-Disposition: form-data; name=<span class="string">"submit-name"</span></span><br><span class="line"></span><br><span class="line">Larry</span><br><span class="line">--$&#123;bound&#125;</span><br><span class="line">Content-Disposition: form-data; name=<span class="string">"files"</span></span><br><span class="line">Content-Type: multipart/mixed; boundary=$&#123;sub_bound&#125;</span><br><span class="line"></span><br><span class="line">--$&#123;sub_bound&#125;</span><br><span class="line">Content-Disposition: file; filename=<span class="string">"file1.txt"</span></span><br><span class="line">Content-Type: text/plain</span><br><span class="line"></span><br><span class="line">... contents of file1.txt ...</span><br><span class="line">--$&#123;sub_bound&#125;</span><br><span class="line">Content-Disposition: file; filename=<span class="string">"file2.gif"</span></span><br><span class="line">Content-Type: image/gif</span><br><span class="line">Content-Transfer-Encoding: binary</span><br><span class="line"></span><br><span class="line">...contents of file2.gif...</span><br><span class="line">--$&#123;sub_bound&#125;--</span><br><span class="line">--$&#123;bound&#125;--</span><br></pre></td></tr></table></figure>

<p>所以解析multipart请求就是根据http协议获取相应信息并转成相应的bean。</p>
<p>相关资料：<a href="https://stackoverflow.com/questions/16958448/what-is-http-multipart-request" target="_blank" rel="noopener">What is http multipart request?</a></p>
<h3 id="7-3-StandardServletMultipartResolver-分析"><a href="#7-3-StandardServletMultipartResolver-分析" class="headerlink" title="7.3 StandardServletMultipartResolver 分析"></a>7.3 StandardServletMultipartResolver 分析</h3><p>StandardServletMultipartResolver 是一个相对陌生的multipart解析器，为什么陌生？因为它是基于Servlet 3.0标准的，而tomcat自1.7开始才支持3.0标准。所以以前的很多教程都是基于 CommonsMultipartResolver 来讲解的。</p>
<p>那Servlet 3.0标准提供了什么呢？它提供了以下这些功能</p>
<img src="http://www.plantuml.com/plantuml/svg/bK_D2i8m3BxtANASA3w1U151JufxWbZZLgrDRTCfYE_kffieY6WE8NnyF_cKHxt7Wc275Pw7aK9bIOQbY8UBKb2FSK9XYvfWLgFvWx6YOw8eDGVQwSEQsH8wm2GbEJ4QXR8tJVJi8a5eZnv86VWKORwOdZLvCUm6BVa9l0JujBP6GyLc0vOBux9SWd45fFflXmSQG0juZF74OVDC-EBQsN6Ix1V-XAqbtO2Z9GOPGq7I737xsEURLIFhv5sNfiSVHjVxLbTr0m00">

<p>其中需要我们关注的时最后两个方法，凡是实现Servlet 3.0标准的容器，都能够直接解析multipart请求，而解析的结果放到了Part接口实现类中。我们没法直接看到Part接口实现类，原因是实现类是容器实现的，也就是tomcat实现的。</p>
<p>而Spring做的事情是什么？判断是否是multipart请求，然后把Part列表中的数据文件放到他的bean结构中。</p>
<h3 id="7-4-multipart数据映射"><a href="#7-4-multipart数据映射" class="headerlink" title="7.4 multipart数据映射"></a>7.4 multipart数据映射</h3><p>还记得第4章讲的HandlerAdapter吗？4.6.1节讲到 RequestMappingHandler 中 HandlerMethodArgumentResolver接口，它的作用就是从request请求中匹配合适的入参。</p>
<p>如果使用multipart请求对应的<code>MultipartFile</code>文件对象，都是通过<code>RequestParamMethodArgumentResolver</code>映射出来的。它实际上做的就是判断是不是multipart请求，如果是，尝试从multipartRequest中获取<code>MultipartFile</code>对象。</p>
<p>如果你想直接使用<code>MultipartRequest</code>对象，则是通过<code>ServletRequestMethodArgumentResolver</code>映射得来的。</p>
<h3 id="7-5-小结"><a href="#7-5-小结" class="headerlink" title="7.5 小结"></a>7.5 小结</h3><p>这一章感觉讲的比较粗糙，但要点还是讲到了，实际上不管采用哪一个multipartResolver实现类，它的作用就是将multipart请求中的内容转化为Spring自己的参数，然后使用<code>HandlerMethodArgumentResolver</code>实现类映射到开发者写的方法入参上。</p>
<p>CommonsMultipartResolver 使用的时apache-common-fileupload包中的功能实现<strong>multipart请求</strong>转化为apache-common-fileupload自己的对象列表，进而被Spring转化为自己的对象列表。</p>
<p>而 StandardServletMultipartResolver 直接利用了Servlet3.0标准提供的getParts功能直接获取内容列表，然后转化为自己的对象列表。</p>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Gavin Zhang
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.gavinzh.com/2018/08/29/learn-springmvc-code-5/" title="SpringMVC 解毒5">http://blog.gavinzh.com/2018/08/29/learn-springmvc-code-5/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/springmvc/" rel="tag"># springmvc</a>
          
            <a href="/tags/spring/" rel="tag"># spring</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/23/what-is-hashcode-of-java/" rel="next" title="java默认的hashcode方法到底得到的是什么？">
                <i class="fa fa-chevron-left"></i> java默认的hashcode方法到底得到的是什么？
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/12/08/Java-code-optimization/" rel="prev" title="Java代码的一些优化思路">
                Java代码的一些优化思路 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="https://avatars3.githubusercontent.com/u/5567916" alt="Gavin Zhang">
            
              <p class="site-author-name" itemprop="name">Gavin Zhang</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">129</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">158</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/jiangmitiao" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:me at gavinzh.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#7-MultipartResolver"><span class="nav-number">1.</span> <span class="nav-text">7 MultipartResolver</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#7-1-MultipartResolver-分析"><span class="nav-number">1.1.</span> <span class="nav-text">7.1 MultipartResolver 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-2-CommonsMultipartResolver-分析"><span class="nav-number">1.2.</span> <span class="nav-text">7.2 CommonsMultipartResolver 分析</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#7-2-1-CommonsMultipartResolver-初始化分析"><span class="nav-number">1.2.1.</span> <span class="nav-text">7.2.1 CommonsMultipartResolver 初始化分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#7-2-2-CommonsMultipartResolver-属性设置分析"><span class="nav-number">1.2.2.</span> <span class="nav-text">7.2.2 CommonsMultipartResolver 属性设置分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#7-2-3-CommonsMultipartResolver-处理请求分析"><span class="nav-number">1.2.3.</span> <span class="nav-text">7.2.3 CommonsMultipartResolver 处理请求分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#7-2-4-CommonsMultipartResolver-结束请求分析"><span class="nav-number">1.2.4.</span> <span class="nav-text">7.2.4 CommonsMultipartResolver 结束请求分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#7-2-5-什么是multipart请求"><span class="nav-number">1.2.5.</span> <span class="nav-text">7.2.5 什么是multipart请求</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-3-StandardServletMultipartResolver-分析"><span class="nav-number">1.3.</span> <span class="nav-text">7.3 StandardServletMultipartResolver 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-4-multipart数据映射"><span class="nav-number">1.4.</span> <span class="nav-text">7.4 multipart数据映射</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-5-小结"><span class="nav-number">1.5.</span> <span class="nav-text">7.5 小结</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2013 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Gavin Zhang</span>

  

  
</div>





<div>
	<a href="http://www.beian.miit.gov.cn/" target="_blank">陕ICP备17010002号-1</a>
</div>





        




  <script type="text/javascript">
    (function() {
      var hm = document.createElement("script");
      hm.src = "//tajs.qq.com/stats?sId=61868582";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1261805793&web_id=1261805793" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>





  



  






  













  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fastclick/1.0.6/fastclick.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.0"></script>



  


  

    
      <script id="dsq-count-scr" src="https://zhang-hengs-website-blog.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://blog.gavinzh.com/2018/08/29/learn-springmvc-code-5/';
          this.page.identifier = '2018/08/29/learn-springmvc-code-5/';
          this.page.title = 'SpringMVC 解毒5';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://zhang-hengs-website-blog.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("EhAMmIXTRGtethTcgYwA9afH-gzGzoHsz", "jzP1TaBhMleAUgPLXyB0h8oQ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=6.0.0"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=6.0.0"></script>


  

</body>
</html>
